package com.esunny.resourcevisualization.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esunny.resourcevisualization.domain.entity.UserGroup;
import com.esunny.resourcevisualization.domain.response.ReturnStructure;
import com.esunny.resourcevisualization.manage.UserGroupManage;
import com.esunny.resourcevisualization.proxy.ZentaoSSOProxy;
import com.esunny.resourcevisualization.service.UserGroupService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @version 1.0.0.0
 * @ClassName UserGroupServiceImpl
 * @Description 用户组逻辑处理实现
 * @Author baochencong
 * @Date 2020/11/5 14:26
 */
@Service
public class UserGroupServiceImpl implements UserGroupService {

    @Resource
    private UserGroupManage userGroupManage;

    @Override
    public ReturnStructure updateUserGroup() {
        List<UserGroup> userGroupList = getGroupListFromZenTao();
        userGroupManage.deleteAllUserGroup();
        userGroupManage.addUserGroupList(userGroupList);
        return ReturnStructure.SUCCESS("更新用户组列表成功", null);
    }

    @Override
    public UserGroup getUserGroupById(int id) {
        return userGroupManage.getUserGroupById(id);
    }

    @Override
    public List<UserGroup> getUserGroupList() {
        return userGroupManage.getUserGroupList();
    }

    /**
     * 从禅道获取用户组列表信息
     *
     * @return 禅道用户组列表信息
     */
    private List<UserGroup> getGroupListFromZenTao() {
        List<UserGroup> userGroupList = new ArrayList<>();

        JSONObject userGroupListInfo = ZentaoSSOProxy.post("/esgroup/list", new HashMap<>());
        System.out.println(userGroupListInfo);
        JSONArray groupListJSONArray = userGroupListInfo.getJSONObject("data").getJSONArray("groupList");
        for (int groupIndex = 0; groupIndex < groupListJSONArray.size(); groupIndex++) {
            JSONObject userGroupJSONObject = groupListJSONArray.getJSONObject(groupIndex);
            UserGroup userGroup = new UserGroup();
            userGroup.setUserGroupName(userGroupJSONObject.getString("name"));
            userGroupList.add(userGroup);
        }

        return userGroupList;
    }
}
